import { Injectable } from '@nestjs/common';
import { CommonService } from '../common/common.service';
import AlipaySdk from 'alipay-sdk';
import * as url from 'url'
@Injectable()
export class AlipayService {
    constructor(
        private readonly common:CommonService,
    ){

    }

    config() {
        return this.common.alipayConf
    }

    Alipay() {
        const conf:any = this.config()
        if(!conf) return null

        return new AlipaySdk({
            appId: conf.appId,
            // keyType: 'PKCS1', // 默认值。请与生成的密钥格式保持一致，参考平台配置一节
            privateKey: conf.privateKey,
            alipayPublicKey: conf.alipayPublicKey
        });
        
    }

    checkNotifySign(data) {
        return this.Alipay().checkNotifySign(data)
    }

    async login(code:string) {
        let alipaySdk = this.Alipay()
        if(!alipaySdk) return null
        return alipaySdk.exec('alipay.system.oauth.token', {
            format : 'json',
            sign_type : 'RSA2',
            grant_type : 'authorization_code',
            code : code
        })
    }

    async createTrade(total_amount:string|number, out_trade_no:string, openid:string, subject:string, notify_url:string) {
        let alipaySdk = this.Alipay()
        if(!alipaySdk) return null

        const conf:any = this.config()

        let baseNotifyUrl = conf.notifyUrl
        if(baseNotifyUrl.endsWith('/') == false) {
            baseNotifyUrl += '/'
        }


        const res = await alipaySdk.exec('alipay.trade.create', {
            notify_url : url.resolve(baseNotifyUrl, notify_url),
            product_code : 'JSAPI_PAY',
            bizContent : {
                out_trade_no,
                total_amount,
                subject,
                buyer_id:openid
            }
        })

        return res.code == '10000' ? res : null
    }
}
